package com.techstar.ats.netty.handler;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import com.techstar.ats.MessageType;
import com.techstar.ats.dxp.AtsMessage;
import com.techstar.ats.dxp.AtsResponse;
import com.techstar.ats.netty.ASDU;
import com.techstar.ats.netty.ASDUCodec;

public class AtsResponseDecoder extends ReplayingDecoder<ReadState> {
	private final ASDU asdu = new ASDU();
	private ByteBuf cacheBuf = null;

	public AtsResponseDecoder() {
		super(ReadState.HEAD);
	}

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		switch(this.state()) {
			case HEAD:
				ASDUCodec.INSTANCE.decode(in, this.asdu);
				this.checkpoint(ReadState.BODY);
				this.cacheBuf = ctx.alloc()
					.buffer(this.asdu.len - 8, this.asdu.len - 8);
				break;
			case BODY:
				try {
					this.cacheBuf.writeBytes(in, Math.min(this.asdu.len - 8, in.readableBytes()));
				} catch(Exception var6) {
					ctx.close();
					throw new Exception(var6);
				}

				if(this.cacheBuf.writableBytes() > 0) {
					this.checkpoint(ReadState.BODY);
				} else {
					this.checkpoint(ReadState.HEAD);
					if(MessageType.NULL != this.asdu.type) {
						AtsResponse value = this.asdu.type.decoder.get(this.cacheBuf);
						if(value instanceof AtsMessage) {
							AtsMessage message = (AtsMessage) value;
							message.id = this.asdu.type.value();
						}

						out.add(value);
					}

					this.cacheBuf.release();
				}
		}

	}
}
